<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Group
 *
 * @author Khoi
 */
class Group {

    //put your code here
    public $id;
    public $name;
    public $userId;

    public static function withId($id) {
        $instance = new self();
        $db = Database::getInstance();
        $query = "SELECT * FROM taggroups WHERE id = $id";
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 1) {
                $rows = $result->dataTable->rows[0];
                $instance->id = $rows["id"];
                $instance->name = $rows["name"];
                $instance->userId = $rows["userid"];
                return $instance;
            }
            return null;
        }
        return null;
    }

    public function save() {
        $db = Database::getInstance();
        if ($this->id) {
            $query = "UPDATE taggroups SET name='$this->name' WHERE id=$this->id";
            $result = $db->query($query);
            if ($result->returnCode == 200)
                return true;
            return false;
        }
        else {
            $query = "INSERT INTO taggroups (id, name, userid) VALUES ($this->id, '$this->name', $this->userId)";
            $result = $db->query($query);
            if ($result->returnCode == 200)
                return true;
            return false;
        }
    }

    public function delete() {
        $db = Database::getInstance();
        $query = "DELETE FROM taggroups WHERE id=$this->id";
        $result = $db->query($query);
        $query = "DELETE FROM tags WHERE groupid=$this->id";
        $result = $db->query($query);
        if ($result->returnCode == 200)
            return true;
        return false;
    }

}
